/*核心的两个函数
func Marshal(v interface{}) ([]byte, error)
将struct编码成xml，可以接收任意类型
func Unmarshal(data []byte, v interface{}) error
将xml转码成struct结构体
两个核心结构体
type Decoder struct {
	...
}
从输入流读取并解析xml
type Encoder struct {
	// contains filtered or unexpected fields
}*/

package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

type Perwson struct {
	XMLName xml.Name `xml:"person"`
	Name    string   `xml:"name"`
	Age     int      `xml:"age"`
	Email   string   `xml:"email"`
}

// 写xml到输出流
func Marshala() {
	p := Perwson{
		Name:  "tom",
		Age:   20,
		Email: "tom@gmail.com",
	}
	// b, _ := xml.Marshal(p)
	// 有缩进格式
	b, _ := xml.MarshalIndent(p, " ", "  ")
	fmt.Printf("%v\n", string(b))
}

//读写文件

func read() {
	/*
		<?xml version="1.0 encoding="YTF-8>
		 <person>
		   <name>tom</name>
		   <age>20</age>
		   <email>tom@gmail.com</email>
		 </person>
	*/
	b, _ := ioutil.ReadFile("a.xml")
	var p Perwson
	xml.Unmarshal(b, &p)
	fmt.Printf("p: %v\n", p)
}

func writek() {
	p := Perwson{
		Name:  "tom",
		Age:   20,
		Email: "tom@gmail.com",
	}

	f, _ := os.OpenFile("b.xml", os.O_WRONLY, 0777)
	defer f.Close()
	e := xml.NewEncoder(f)
	e.Encode(p)

}

func main() {
	Marshala()
}
